#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>

struct sockaddr_in server;

using namespace std;

static void Usage(string name)
{
    cout << "Usage:" << name << "server_ip server_port" << endl;
}

void* RecverAndPrint(void* args)
{
    while (true)
    {
        int sock = *(int*)args;
        char buffer[1024];
        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        ssize_t s = recvfrom(sock, buffer, sizeof(buffer) - 1,
                            0, (struct sockaddr*)&tmp, &len);
        if (s > 0)
        {
            buffer[s] = 0;
            cout << "server echo# " << buffer << endl;
        }
    }
}

int main(int argc , char* argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());
    server.sin_port = htons(server_port);
    pthread_t t;
    pthread_create(&t,nullptr, RecverAndPrint, &sockfd);
    string buffer;
    while (true)
    {
        cerr << "Please Enter# "; 
        getline(cin, buffer);
        sendto(sockfd, buffer.c_str(), buffer.size(), 0,
                (const struct sockaddr*)&server, sizeof(server));
    }
    close (sockfd);
    return 0;
}
